package com.zlht.controller;

import com.zlht.entity.Author;
import com.zlht.entity.Store;
import com.zlht.service.AuthorService;
import com.zlht.service.imp.AuthorServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/author")
public class AuthorServlet extends HttpServlet {

    AuthorService authorService = new AuthorServiceImp();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        switch (method) {
            case "list":
                req.setAttribute("list", this.authorService.list());
                req.getRequestDispatcher("authormanager.jsp").forward(req, resp);
                break;
            case "search":
                String key = req.getParameter("key");
                String value = req.getParameter("value");
                req.setAttribute("list",this.authorService.search(key ,value));
                req.getRequestDispatcher("authormanager.jsp").forward(req, resp);
                break;
            case "save":
                String name = req.getParameter("name");
                String gender = req.getParameter("gender");
                String country = req.getParameter("country");
                String introduce = req.getParameter("introduce");
                this.authorService.save(new Author(name,gender,country,introduce));
                resp.sendRedirect("/author?method=list");
                break;
            case "update":
                String idStr = req.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                name = req.getParameter("name");
                gender = req.getParameter("gender");
                country = req.getParameter("country");
                introduce = req.getParameter("introduce");
                this.authorService.update(new Author(id,name,gender,country,introduce));
                resp.sendRedirect("/author?method=list");
                break;
            case "delete":
                idStr = req.getParameter("id");
                id = Integer.parseInt(idStr);
                this.authorService.delete(id);
                resp.sendRedirect("/author?method=list");
                break;
        }
    }
}
